package com.mashen.util;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

public class ImageUtil {
	
	/**
	 * 加载本地图片到缓冲区
	 * @param path
	 * @return
	 */
	public static BufferedImage getLocalPic(String path){
		try {
			return ImageIO.read(new File(path));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 加载网络图片到缓冲区
	 * @param path
	 * @return
	 */
	public static BufferedImage getNetPic(String url){
		try {
			return ImageIO.read(new URL(url));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 合并图片
	 * @param bgimage
	 * @param imge
	 * @return
	 */
	public static boolean combine(BufferedImage bgimage,
			BufferedImage imge,int x,int y,int width,int height){
		Graphics2D g2d=bgimage.createGraphics();
		g2d.drawImage(imge, x, y, width, height, null);
		g2d.dispose();
		return true;
	}
	/**
	 * 保存图片
	 * @param image
	 * @return
	 */
	public static void saveImage(BufferedImage image,String savepath){
		FileOutputStream ouput=null;
		try {
			ouput=new FileOutputStream(savepath);
			ImageIO.write(image,"jpg",ouput);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(ouput!=null){
				try {
					ouput.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String url="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFt8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xLzZUbDFMUW5rTW50THYyQVRpQmVFAAIE4w17VwMEAI0nAA==";
		BufferedImage bgimage=getLocalPic("d:/bg.jpg");
		BufferedImage headimage=getLocalPic("d:/head.jpg");
		BufferedImage qrcodeimage=getNetPic(url);
		combine(bgimage,headimage,120,680,120,120);
		combine(bgimage,qrcodeimage,320,680,120,120);
		saveImage(bgimage,"d:\\newimag.jpg");
		
	}

}
